import tkinter as tk
from switchnet import SwitcheNet


class ToggleSwitch(tk.Canvas):
    def __init__(
        self,
        master,
        width=60,
        height=30,
        bg="white",
        fg="black",
        active_bg="green",
        inactive_bg="gray",
        command=None,
        initial_state=False,
    ):
        super().__init__(
            master, width=width, height=height, bg=bg, highlightthickness=0
        )

        self.width = width
        self.height = height
        self.fg = fg
        self.active_bg = active_bg
        self.inactive_bg = inactive_bg
        self.command = command
        self.state = initial_state

        # 绘制开关
        self.draw_switch()

        # 绑定点击事件
        self.bind("<Button-1>", self.toggle)

    def draw_switch(self):
        self.delete("all")

        # 绘制背景
        bg_color = self.active_bg if self.state else self.inactive_bg
        self.create_rectangle(
            2,
            2,
            self.width - 2,
            self.height - 2,
            fill=bg_color,
            outline=self.fg,
            width=2,
        )

        # 绘制滑块
        slider_x = self.width - 20 if self.state else 20
        self.create_oval(
            5,
            5,
            self.height - 5,
            self.height - 5,
            fill="white",
            outline=self.fg,
            width=2,
        )
        self.create_oval(
            slider_x - 15,
            5,
            slider_x + 5,
            self.height - 5,
            fill="white",
            outline=self.fg,
            width=2,
        )

    def toggle(self, event=None):
        self.state = not self.state
        self.draw_switch()
        if self.command:
            self.command(self.state)

    def get_state(self):
        return self.state

    def set_state(self, state):
        if self.state != state:
            self.state = state
            self.draw_switch()


swt = SwitcheNet()


def switch_changed(state):
    if state:
        print("开关状态: 开启 - 执行开启逻辑")
        status_label.config(text="状态: 外网", fg="green")
        # 在这里添加开启状态的业务逻辑
        swt.change("互联网")
        print("sw doe")

    else:
        print("开关状态: 关闭 - 执行关闭逻辑")
        status_label.config(text="状态: 内网", fg="red")
        # 在这里添加关闭状态的业务逻辑

        swt.change("玉溪市政务外网")
        print("sw doe")


root = tk.Tk()
root.title("切换内外网")
root.geometry("300x200")


# 状态显示标签
status_label = tk.Label(root, text="状态: 未联网", font=("Arial", 12), fg="red")
status_label.pack(pady=20)

# 创建自定义 Switch
switch = ToggleSwitch(
    root, active_bg="#4CAF50", inactive_bg="#9E9E9E", command=switch_changed
)
switch.pack(pady=10)

# 测试按钮
test_button = tk.Button(
    root,
    text="测试开关状态",
    command=lambda: print(f"当前开关状态: {'开启' if switch.get_state() else '关闭'}"),
)
test_button.pack(pady=10)

root.mainloop()
